package com.imooc.disruptor.client;

import com.imooc.disruptor.codec.MarshallingCodeCFactory;
import com.imooc.disruptor.entity.TranslatorData;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author yqc 2018/10/16
 */
@Slf4j
public class NettyClient {

    private static final String HOST = "127.0.0.1";
    private static final int POST = 8765;

    private Channel channel;

    /**
     * 1 创建一个工作线程组：用于实际处理业务的线程组
     */
    private EventLoopGroup workGroup = new NioEventLoopGroup();

    private ChannelFuture channelFuture;

    public NettyClient() {
        this.connect(HOST, POST);
    }

    private void connect(String host, int post) {
        //2 辅助类（注意Client和Server不一致）
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.group(workGroup)
                    .channel(NioSocketChannel.class)
                    //表示缓存区动态调配（自适应）
                    .option(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT)
                    //缓冲区池化操作
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());
                            socketChannel.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());
                            socketChannel.pipeline().addLast(new ClientHandler());
                        }
                    });
            //绑定端口，同步等待请求链接
            this.channelFuture = bootstrap.connect(host, post).sync();
            log.info("Client Connected...");

            //接下来就进行数据的发送，但是首先我们要获取通道channel：
            this.channel = channelFuture.channel();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void sendData() {
        for (int i = 0; i < 10; i++) {
            TranslatorData request = new TranslatorData();
            request.setId("" + i);
            request.setName("请求消息名称_" + i);
            request.setMessage("请求消息内容_" + i);

            this.channel.writeAndFlush(request);
        }
    }

    public void close() throws Exception {
        channelFuture.channel().closeFuture().sync();
        //优雅停机
        workGroup.shutdownGracefully();
        log.info("Client Shutdown");
    }
}
